import uvicorn
from fastapi import FastAPI
from fastapi.params import Query, Depends
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session

from api.crud import list_records, count_records, handle_record, delete_record
from api.database import db_session_factory

app = FastAPI()


def get_db_session():
    db_session = db_session_factory()
    try:
        yield db_session
        db_session.commit()
    except SQLAlchemyError:
        db_session.rollback()
    finally:
        db_session.close()


@app.get('/api/records/')
async def search(db: Session = Depends(get_db_session),
                 keyword: str = Query(None, description='查询关键字'),
                 page: int = Query(1, ge=1, description='页码'),
                 size: int = Query(5, ge=5, le=50, description='页面大小')):
    """查询违章记录"""
    records = list_records(db, page, size, keyword)
    count = count_records(db, keyword)
    total_page = (count - 1) // size + 1
    return {'currentPage': page, 'totalPage': total_page, 'results': records}


@app.patch('/api/records/{rno}/')
async def handle(db: Session = Depends(get_db_session),
                 rno: int = Query(None, description='违章记录编号')):
    """受理违章记录"""
    if handle_record(db, rno):
        return {'code': 20000, 'mesg': '受理成功'}
    return {'code': 20001, 'mesg': '受理失败'}


# 依赖注入 Depends(...)
@app.delete('/api/records/{rno}/', status_code=204)
async def remove(db: Session = Depends(get_db_session),
                 rno: int = Query(None, description='违章记录编号')):
    """删除违章记录"""
    if delete_record(db, rno):
        return {'code': 30000, 'mesg': '删除成功'}
    return {'code': 30001, 'mesg': '删除失败'}


if __name__ == '__main__':
    uvicorn.run('api.main:app', host='127.0.0.1', port=8000, reload=True)
